package net.forsalemall.android;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import com.google.android.c2dm.GCMConstants;
import com.markupartist.android.widget.ScrollingTextView;
import com.utils.HttpUtils;
import com.utils.Utils;

import android.app.Activity;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;

public class PushNotificationActivity extends Activity {

	private TextView descView;
	private View buttonContainer;
	private ImageView imageView;
	private byte[] data;
	private String fileName;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		process();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		process();
	}

	private void process() {
		try {

			int notifId = getIntent().getIntExtra(
					GCMConstants.KEY_GCM_NOTIFICATION_ID, -1);
			if (notifId != -1) {
				((NotificationManager) getSystemService(NOTIFICATION_SERVICE))
						.cancel(notifId);
			}
			boolean isDialog = getIntent().getBooleanExtra(GCMConstants.KEY_GCM_IS_DIALOG, true);
			if(isDialog){
				setTheme(android.R.style.Theme_Dialog);
				requestWindowFeature(Window.FEATURE_NO_TITLE);
			}
			setContentView(R.layout.push_notification);
			ScrollingTextView titleView  = (ScrollingTextView)findViewById(R.id.actionbar_title);		
			titleView.setText(getIntent().getStringExtra(GCMConstants.KEY_GCM_TITLE));
			
			
//			actionBar.setHomeLogo(R.drawable.icon);
			buttonContainer = findViewById(R.id.button_container);
			descView = (TextView) findViewById(R.id.desc_view);
			imageView = (ImageView)findViewById(R.id.image_view);
			
			
			String desc = getIntent().getStringExtra(GCMConstants.KEY_GCM_MESSAGE);

			List<String> urls = Utils.getLRLS(desc);
			for (int i = 0; i < urls.size(); i++) {
				String url = urls.get(i);
				desc = desc.replace(url, "<u>" + url + "</u>");
			}
			Spanned text = Html.fromHtml(desc);
			final SpannableStringBuilder strBuilder = new SpannableStringBuilder(
					text);
			UnderlineSpan[] underlines = strBuilder.getSpans(0, text.length(),
					UnderlineSpan.class);
			for (final UnderlineSpan span : underlines) {
				final int start = strBuilder.getSpanStart(span);
				final int end = strBuilder.getSpanEnd(span);
				int flags = strBuilder.getSpanFlags(span);
				ClickableSpan myActivityLauncher = new ClickableSpan() {
					public void onClick(View view) {
						try {
							String url = strBuilder.subSequence(start, end)
									.toString();
							startActivity(new Intent(Intent.ACTION_VIEW,
									Uri.parse(url)));
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				};

				strBuilder.setSpan(myActivityLauncher, start, end, flags);
			}

			descView.setText(strBuilder);
			descView.setMovementMethod(LinkMovementMethod.getInstance());
//			descView.setMovementMethod(ScrollingMovementMethod.getInstance());
			
			
			
			final String imageUrl = getIntent().getStringExtra(GCMConstants.KEY_GCM_IMAGE_URL);
			if(imageUrl!=null && imageUrl.length()>6){
				imageView.setVisibility(View.VISIBLE);
				fileName = imageUrl.substring(imageUrl.lastIndexOf("/"));
				loadImage(imageUrl);
			}
			
			if(isDialog){
				buttonContainer.setVisibility(View.VISIBLE);
				findViewById(R.id.button_close).setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						finish();
					}
				});
				findViewById(R.id.button_save).setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						saveImage();
						v.setEnabled(false);
					}
				});
			}else{
				buttonContainer.setVisibility(View.GONE);
			}
			

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void loadImage(final String imageUrl){
		new AsyncTask<String, String, String>() {
			private ProgressDialog progressDialog;
			
			private Bitmap bitmap;
			protected void onPreExecute() {
				progressDialog = Utils.getProgressDialog(PushNotificationActivity.this, null, getString(R.string.loading));
				
				progressDialog.show();
			}
			protected String doInBackground(String... arg0) {
				try {
					data = HttpUtils.getHttpResponse(imageUrl);
					bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
				} catch (Exception e) {
					e.printStackTrace();
				}
				return null;
			}
			protected void onPostExecute(String unused) {
				progressDialog.dismiss();
				if(bitmap!=null){
					imageView.setImageBitmap(bitmap);
				}
			}
		}.execute();
	}
	
	private void saveImage(){
		try {	
			if(data!=null){
				final File dir = Environment.getExternalStorageDirectory();
				File file = new File(dir, fileName);
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(data);
				fos.close();
				sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ dir)));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
